<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Short Link Service Tester</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }

        .container {
            display: flex;
            flex-direction: column;
            gap: 20px;
        }

        .form-group {
            display: flex;
            flex-direction: column;
            gap: 5px;
        }

        input,
        button {
            padding: 10px;
            font-size: 16px;
        }

        button {
            cursor: pointer;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
        }

        button:hover {
            background-color: #0056b3;
        }

        #result {
            margin-top: 20px;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 4px;
            background-color: #f9f9f9;
        }

        .error {
            color: #dc3545;
        }

        .success {
            color: #28a745;
        }

        #history {
            margin-top: 30px;
        }

        .history-item {
            padding: 10px;
            border-bottom: 1px solid #eee;
        }
    </style>
</head>

<body>
    <div class="container">
        <h1>短连接生成服务</h1>

        <div class="form-group">
            <label for="url">输入一个长网址进行缩短：</label>
            <input type="url" id="url" placeholder="https://example.com/very/long/url" required>
        </div>

        <button id="shorten-btn">缩短URL</button>

        <div id="result" style="display: none;"></div>

        <div id="history">
            <h2>最近创建的短链接</h2>
            <div id="history-list"></div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', () => {
            const urlInput = document.getElementById('url');
            const shortenBtn = document.getElementById('shorten-btn');
            const resultDiv = document.getElementById('result');
            const historyList = document.getElementById('history-list');
            const baseUrl = "http:127.0.0.1:3000"
            // 从本地存储加载历史记录
            loadHistory();

            shortenBtn.addEventListener('click', async () => {
                const longUrl = urlInput.value.trim();

                if (!longUrl) {
                    showResult('请输入一个URL', false);
                    return;
                }

                try {
                    const response = await fetch(baseUrl + '/v1/links', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ url: longUrl })
                    });

                    if (!response.ok) {
                        const error = await response.json();
                        throw new Error(error.error || '缩短URL失败');
                    }

                    const data = await response.json();
                    showResult(`
                        <p>短链接创建成功！</p>
                        <p>短代码: <strong>${data.short_code}</strong></p>
                        <p>短链接: <a href="${data.short_url}" target="_blank">${data.short_url}</a></p>
                        <button onclick="copyToClipboard('${data.short_url}')">复制链接</button>
                    `, true);

                    // 保存到历史记录
                    saveToHistory(data);
                } catch (error) {
                    showResult(error.message, false);
                }
            });

            function showResult(message, isSuccess) {
                resultDiv.style.display = 'block';
                resultDiv.innerHTML = message;
                resultDiv.className = isSuccess ? 'success' : 'error';
            }

            function saveToHistory(data) {
                let history = JSON.parse(localStorage.getItem('shortLinkHistory') || '[]');

                // 添加到历史记录开头
                history.unshift({
                    short_code: data.short_code,
                    short_url: data.short_url,
                    original_url: urlInput.value,
                    timestamp: new Date().toISOString()
                });

                // 只保留最近的10条记录
                if (history.length > 10) {
                    history = history.slice(0, 10);
                }

                localStorage.setItem('shortLinkHistory', JSON.stringify(history));
                loadHistory();
            }

            function loadHistory() {
                const history = JSON.parse(localStorage.getItem('shortLinkHistory') || '[]');

                if (history.length === 0) {
                    historyList.innerHTML = '<p>暂无历史记录...</p>';
                    return;
                }

                historyList.innerHTML = history.map(item => `
                <div class="history-item">
                    <p><strong>短链接:</strong> <a href="${item.short_url}" target="_blank">${item.short_url}</a></p>
                    <p><strong>原始URL:</strong> ${item.original_url}</p>
                    <p><small>创建时间: ${new Date(item.timestamp).toLocaleString()}</small></p>
                </div>
                `).join('');
            }
        });

        // 全局函数用于复制到剪贴板
        function copyToClipboard(text) {
            navigator.clipboard.writeText(text).then(() => {
                alert('已复制到剪贴板！');
            }).catch(err => {
                console.error('复制失败:', err);
            });
        }
    </script>
</body>

</html>